
// 在页面加载完成后执行的函数中添加加载分类的代码
document.addEventListener('DOMContentLoaded', function() {
    // 初始化时间显示
    getTime();
    // 设置定时更新时间
    window.setInterval(getTime, 1000);
    
    // 获取图书数据
    getHotBooks();
    getRecommendBooks();
    getFlashSaleBooks();
    
    // 加载分类数据
    loadCategories();

    loadHotBooksForCarousel();
    
});

// 获取热销图书
function getHotBooks() {
    ApiService.book.getHotBooks()
        .then(response => {
            if (response.data && response.data.length > 0) {
                renderHotBooks(response.data);
            }
        })
        .catch(error => {
            console.error("获取热销图书失败:", error);
        });
}

// 获取推荐图书
function getRecommendBooks() {
    ApiService.book.getRecommendBooks()
        .then(response => {
            if (response.data && response.data.length > 0) {
                renderRecommendBooks(response.data);
            }
        })
        .catch(error => {
            console.error("获取推荐图书失败:", error);
        });
}

// 获取抢购图书
function getFlashSaleBooks() {
    ApiService.book.getFlashSaleBooks()
        .then(response => {
            if (response.data && response.data.length > 0) {
                renderFlashSaleBooks(response.data);
            }
        })
        .catch(error => {
            console.error("获取抢购图书失败:", error);
        });
}

// 渲染热销图书
function renderHotBooks(books) {
    const container = document.querySelector('.hotTitle').nextElementSibling;
    if (!container) return;
    
    let html = '';
    books.slice(0, 10).forEach(book => {
        html += `
        <div class="booksItem" onclick="detail(${book.id})">
            <img src="${book.imageUrl || './img/default-book.jpg'}" alt="${book.title}">
            <div class="booksInfo">${book.description || '暂无描述'}</div>
            <div class="booksPrice">￥${book.price || '0.00'}</div>
        </div>
        `;
    });
    
    if (html) {
        container.innerHTML = html;
    }
}

// 渲染推荐图书
function renderRecommendBooks(books) {
    const container = document.querySelector('.likeTitle').nextElementSibling;
    if (!container) return;
    
    let html = '';
    books.slice(0, 10).forEach(book => {
        html += `
        <div class="booksItem" onclick="detail(${book.id})">
            <img src="${book.imageUrl || './img/default-book.jpg'}" alt="${book.title}">
            <div class="booksInfo">${book.description || '暂无描述'}</div>
            <div class="booksPrice">￥${book.price || '0.00'}</div>
        </div>
        `;
    });
    
    if (html) {
        container.innerHTML = html;
    }
}

// 渲染抢购图书
function renderFlashSaleBooks(books) {
    const container = document.querySelector('.booksList');
    if (!container) return;
    
    let html = '';
    books.slice(0, 10).forEach(book => {
        // 随机生成抢购百分比
        const percent = Math.floor(Math.random() * 90) + 10;
        
        html += `
        <div class="booksItem" onclick="detail(${book.id})">
            <img src="${book.imageUrl || './img/default-book.jpg'}" alt="${book.title}">
            <div class="empty5"></div>
            <div class="layui-progress progress">
                <div class="layui-progress-bar layui-bg-red" lay-percent="${percent}%"></div>
            </div>
            <div class="empty5"></div>
            <div class="booksInfo font14 colorRed">已抢购${percent}%</div>
            <div class="sale">
                <div class="booksPrice">￥${book.price || '0.00'}</div>
                <div class="SalePrice"><del>￥${(book.price * 1.2).toFixed(2)}</del></div>
            </div>
        </div>
        `;
    });
    
    if (html) {
        container.innerHTML = html;
    }
    
    // 重新渲染进度条
    layui.use('element', function(){
        var element = layui.element;
        element.init();
    });
}


// 获取当前时间
function getTime() {
    let time = document.getElementById('time');
    if (!time) return;
    
    let date = new Date();
    let y = date.getFullYear();
    let m = date.getMonth() + 1;
    let d = date.getDate();
    let h = date.getHours();
    let mn = date.getMinutes();
    let s = date.getSeconds();
    
    // 格式化时间，保证两位数显示
    m = m < 10 ? '0' + m : m;
    d = d < 10 ? '0' + d : d;
    h = h < 10 ? '0' + h : h;
    mn = mn < 10 ? '0' + mn : mn;
    s = s < 10 ? '0' + s : s;
    
    let timeText = [y, m, d].join('-') + ' ' + [h, mn, s].join(':');
    time.innerHTML = timeText;
}

// 跳转到详情页
function detail(id) {
    if (!id) return;
    window.location.href = `./detail.html?id=${id}`;
}

// 加载分类数据
function loadCategories() {
    ApiService.category.getAllCategories()
        .then(response => {
            if (response.data && response.data.length > 0) {
                renderCategories(response.data);
            }
        })
        .catch(error => {
            console.error("获取分类数据失败:", error);
        });
}

// 渲染分类数据
function renderCategories(categories) {
    const menuElement = document.getElementById('demo-menu');
    if (!menuElement) return;
    
    // 清空现有内容
    menuElement.innerHTML = '';
    
    // 渲染分类
    categories.forEach(category => {
        const categoryElement = createCategoryElement(category);
        menuElement.appendChild(categoryElement);
    });
    
    // 重新初始化Layui菜单
    // layui.use('dropdown', function(){
    //     var dropdown = layui.dropdown;
    //     dropdown.render({
    //         elem: '#demo-menu',
    //         trigger: 'hover'
    //     });
    // });
}

// 创建分类元素
function createCategoryElement(category) {
    const li = document.createElement('li');
    li.className = 'layui-menu-item-parent';
    li.setAttribute('lay-options', "{type: 'parent'}");
    
    // 创建分类标题
    const titleDiv = document.createElement('div');
    titleDiv.className = 'layui-menu-body-title';
    titleDiv.textContent = category.categoryName;
    
    // 如果有子分类，添加右箭头图标
    if (category.children && category.children.length > 0) {
        const icon = document.createElement('i');
        icon.className = 'layui-icon layui-icon-right';
        titleDiv.appendChild(icon);
        
        // 创建子分类面板
        const panelDiv = document.createElement('div');
        panelDiv.className = 'layui-panel layui-menu-body-panel';
        
        const ul = document.createElement('ul');
        
        // 渲染子分类
        category.children.forEach(child => {
            const childLi = document.createElement('li');
            
            // 如果子分类还有子分类，设置为父分类样式
            if (child.children && child.children.length > 0) {
                childLi.className = 'layui-menu-item-parent';
                childLi.setAttribute('lay-options', "{type: 'parent'}");
                
                const childTitleDiv = document.createElement('div');
                childTitleDiv.className = 'layui-menu-body-title';
                childTitleDiv.textContent = child.categoryName;
                
                childLi.appendChild(childTitleDiv);
                
                // 递归创建子分类
                const childPanelDiv = document.createElement('div');
                childPanelDiv.className = 'layui-panel layui-menu-body-panel';
                
                const childUl = document.createElement('ul');
                
                child.children.forEach(grandChild => {
                    const grandChildLi = document.createElement('li');
                    const grandChildDiv = document.createElement('div');
                    grandChildDiv.className = 'layui-menu-body-title';
                    grandChildDiv.textContent = grandChild.categoryName;
                    
                    // 添加点击事件，跳转到分类页面
                    grandChildDiv.addEventListener('click', function() {
                        window.location.href = `./catalog.html?categoryId=${grandChild.id}`;
                    });
                    
                    grandChildLi.appendChild(grandChildDiv);
                    childUl.appendChild(grandChildLi);
                });
                
                childPanelDiv.appendChild(childUl);
                childLi.appendChild(childPanelDiv);
            } else {
                // 没有子分类，直接显示
                const childDiv = document.createElement('div');
                childDiv.className = 'layui-menu-body-title';
                childDiv.textContent = child.categoryName;
                
                // 添加点击事件，跳转到分类页面
                childDiv.addEventListener('click', function() {
                    window.location.href = `./catalog.html?categoryId=${child.id}`;
                });
                
                childLi.appendChild(childDiv);
            }
            
            ul.appendChild(childLi);
        });
        
        panelDiv.appendChild(ul);
        li.appendChild(titleDiv);
        li.appendChild(panelDiv);
    } else {
        // 没有子分类，直接显示
        li.appendChild(titleDiv);
        
        // 添加点击事件，跳转到分类页面
        titleDiv.addEventListener('click', function() {
            window.location.href = `./category.html?id=${category.id}`;
        });
    }
    
    return li;
}

// 初始化轮播图
function initCarousel() {
    layui.use(function() {
        var carousel = layui.carousel;
        // 渲染轮播图
        carousel.render({
            elem: '#ID-carousel-demo-image',
            width: '100%',
            height: '400px',
            interval: 3000
        });
    });
}

// 加载热门图书数据并设置轮播图
function loadHotBooksForCarousel() {
    // 调用API获取热门图书
    ApiService.book.getHotBooks()
        .then(response => {
            const books = response.data || [];
            if (books.length > 0) {
                // 获取轮播容器
                const carouselContainer = document.getElementById('carousel-container');
                // 清空现有内容
                carouselContainer.innerHTML = '';
                
                // 添加每本书的封面到轮播图
                books.forEach(book => {
                    const div = document.createElement('div');
                    div.innerHTML = `
                        <a href="./detail.html?id=${book.id}" title="${book.title}">
                            <img src="${book.imageUrl || './img/default-book.jpg'}" alt="${book.title}">
                        </a>
                    `;
                    carouselContainer.appendChild(div);
                });
                
                // 重新初始化轮播图
                initCarousel();
            }
        })
        .catch(error => {
            console.error('获取热门图书失败:', error);
            // 加载失败时使用默认图片
            const carouselContainer = document.getElementById('carousel-container');
            carouselContainer.innerHTML = `
                <div><img src="./img/lunbo1.jpg"></div>
                <div><img src="./img/lunbo2.jpg"></div>
                <div><img src="./img/lunbo3.jpg"></div>
                <div><img src="./img/lunbo4.jpg"></div>
                <div><img src="./img/lunbo5.jpg"></div>
            `;
            initCarousel();
        });
}